package j.framework.tags.form;

import j.util.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;

/**
 * User: jason
 * Date: 2014/12/17 16:14
 */
public class FormTagWriter {
    private JspWriter writer;
    public FormTagWriter(JspWriter writer){
        this.writer = writer;
    }

    public void writeFormTagProperty(String propertyName,String propertyValue)
        throws JspException{
        if (StringUtils.isNotEmpty(propertyValue)) {
            try {
                writer.write(" ");
                writer.write(propertyName);
                writer.write("=\"");
                writer.write(propertyValue);
                writer.write("\"");
            }catch (IOException e){
                throw new JspException(e.getMessage());
            }
        }
    }

    public void writeSomething(String str) throws JspException{
        try {
            writer.write(str);
        }catch (IOException e){
            throw new JspException(e.getMessage());
        }
    }

    /**
     * 仅输出tag的开始标记及标记名称tagName，如:<form
     * @param tagName
     * @throws java.io.IOException
     */
    public void beginTag(String tagName)throws JspException {
        try {
            writer.write("<");
            writer.write(tagName);
        }catch (IOException e){
            throw new JspException(e.getMessage());
        }
    }

    /**
     * 仅输出tag的开始的结束，不是关闭标记，如：>
     * @throws java.io.IOException
     */
    public void endTag()throws JspException{
        try {
            writer.write(">");
        }catch (IOException e){
            throw new JspException(e.getMessage());
        }
    }

    /**
     * 关闭没有体的标记，如：/>
     * @throws java.io.IOException
     */
    public void closeBlankTag()throws JspException{
        try {
            writer.write("/>");
        }catch (IOException e){
            throw new JspException(e.getMessage());
        }
    }

    /**
     * 关闭有体的标记，需要指定标记名称，如</form>
     * @param tagName
     * @throws java.io.IOException
     */
    public void closeTag(String tagName)throws JspException{
        try {
            writer.write("</");
            writer.write(tagName);
            writer.write(">");
        }catch (IOException e){
            throw new JspException(e.getMessage());
        }
    }

    public void flush()throws JspException{
        try {
            writer.flush();
        } catch (IOException e) {
            throw new JspException(e.getMessage());
        }
    }
}
